<template>
  <div>
    <el-card class="box-card">
      <el-tabs stretch v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="用户登录" name="login">
          <el-form
            :model="loginForm"
            status-icon
            ref="loginForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                type="text"
                v-model="loginForm.username"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="密 码" prop="password">
              <el-input
                type="password"
                v-model="loginForm.password"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitLoginForm('loginForm')"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="用户注册" name="register">
          <el-form
            :model="registerForm"
            status-icon
            :rules="rules"
            ref="registerForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                type="text"
                v-model="registerForm.username"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮 箱" prop="email">
              <el-input
                type="email"
                v-model="registerForm.email"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="密 码" prop="password">
              <el-input
                type="password"
                v-model="registerForm.password"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPassword">
              <el-input
                type="password"
                v-model="registerForm.checkPassword"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitRegisterForm('registerForm')"
                >提交</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import api from "../api";
import { mapMutations } from "vuex";
import jwtDecode from "jwt-decode";
export default {
  name: "Login",
  data() {
    var validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (value.length < 6) {
        callback(new Error("长度不足6位"));
      } else {
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (value === "") {
        callback(new Error("请输入邮箱!"));
      }else if (!reg.test(value)) {
          callback(new Error('请输入正确的邮箱！'));
      } else {
        callback();
      }
    };
    var validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码!"));
      } else {
        callback();
      }
    };
    var validateCheckPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码!"));
      } else if (value !== this.registerForm.password) {
        callback(new Error("两次输入的密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      activeName: "login",
      loginForm: {
        username: "",
        password: "",
      },
      registerForm: {
        username: "",
        email: "",
        password: "",
        checkPassword: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        email: [{ validator: validateEmail, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        checkPassword: [{ validator: validateCheckPassword, trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapMutations("loginModule", ["updateToken", "updateUsername"]),
    handleClick(key) {},
    /**
     * 登录
     */
    submitLoginForm() {
      api
        .login({
          username: this.loginForm.username,
          password: this.loginForm.password,
        })
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === 200) {
              this.updateToken(res.data.token);
              this.updateUsername(jwtDecode(res.data.token).username);
              localStorage.setItem("ego", JSON.stringify(res.data));
              this.$router.replace("/");
            }else {
              this.$message.error(res.data.msg);
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    /**
     * 注册
     */
    submitRegisterForm() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          api
            .register({
              username: this.registerForm.username,
              password: this.registerForm.password,
              email: this.registerForm.email,
            })
            .then((res) => {
              if (res.status === 200) {
                this.$message({
                  message: res.data.msg,
                  type: 'success'
                })
              } else {
                this.$message.error(res.data.msg);
              }
            });
        } else {
          this.$message.error('请检查格式再提交');
          return false;
        }
      });
    },
  },
};
</script>

<style>
.box-card {
  width: 600px;
  margin: 0 auto;
  margin-top: 100px;
}
</style>